package com.zsl.blog.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.zsl.blog.api.dao.pojo.SysUser;
import com.zsl.blog.api.service.RegisterService;
import com.zsl.blog.api.service.SysUserService;
import com.zsl.blog.api.utils.ErrorCode;
import com.zsl.blog.api.utils.JWTUtils;
import com.zsl.blog.api.vo.Result;
import com.zsl.blog.api.vo.params.RegisterParam;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class RegisterServiceImpl implements RegisterService {
    private static final String SLAT = "zzssll*";
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public Result register(RegisterParam param) {
        SysUser sysUser = sysUserService.findUserByAccount(param.getAccount());
        if (sysUser != null) {
            return Result.fail(ErrorCode.ACCOUNT_EXIST.getCode(), ErrorCode.ACCOUNT_EXIST.getMsg());
        }
        SysUser user = new SysUser();
        user.setNickname(param.getNickName());
        user.setAccount(param.getAccount());
        user.setPassword(DigestUtils.md5Hex(param.getPassword()+SLAT));
        user.setCreateDate(System.currentTimeMillis());
        user.setLastLogin(System.currentTimeMillis());
        user.setAvatar("/static/user/user_1.png");
        user.setAdmin(1);
        user.setSalt("");
        user.setStatus("");
        user.setEmail("");
        sysUserService.register(user);

        String token = JWTUtils.createToken(user.getId());
        redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(user),1, TimeUnit.DAYS);
        return Result.success(token);
    }
}
